package com.mjfeed.controller.admin;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mjfeed.controller.BaseController;
import com.mjfeed.entity.Admin;
import com.mjfeed.entity.Permission;
import com.mjfeed.entity.Role;
import com.mjfeed.service.AdminService;
import com.mjfeed.util.Format;
import com.mjfeed.util.Md5Util;
import com.mjfeed.util.Pagination;
import com.mjfeed.util.ParamBean;

/**
 * @description 后台登录
 * @author zhaominglei
 * @date 2014年10月1日
 */
@Controller("adminAdminController")
@RequestMapping("/admin")
public class AdminController extends BaseController {
	@Resource(name="adminService")
	private AdminService adminService;
	
	@RequestMapping(value = { "/login", "/login/get" }, method=RequestMethod.GET)
	public String get(HttpServletRequest request, HttpServletResponse response, Model model){
		return "admin/login";
	}
	
	@RequestMapping(value = "/login/post", method=RequestMethod.POST)
	public String post(Admin admin, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model){
		String code = (String) session.getAttribute("validateCode");
		String submitCode = WebUtils.getCleanParam(request, "validateCode");
		if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(code, submitCode.toLowerCase())) {
			request.setAttribute("msg", "验证码不正确");
			return "admin/login";
		}
		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), Md5Util.encrypt(admin.getPassword()));
		boolean rememberMe = (request.getParameter("rememberMe") != null && Boolean.valueOf(request.getParameter("rememberMe"))) ? true:false;
		token.setRememberMe(rememberMe);
		try {
			user.login(token);
			return "redirect:/admin/index.shtml";
		}catch (AuthenticationException e) {
			token.clear();
			request.setAttribute("msg", "认证失败，用户名或密码不对");
			return "admin/login";
		}
	}
	
	@RequestMapping(value = { "/logout", "/logout/get" }, method=RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response, Model model){
		Subject user = SecurityUtils.getSubject();
		user.logout();
		return "admin/login";
	}
	
	@RequestMapping(value = "/index", method=RequestMethod.GET)
	public String index(HttpServletRequest request, HttpServletResponse response, Model model){
		return "admin/index";
	}
	
	@RequestMapping(value = "/admin/list", method=RequestMethod.GET)
	public String adminList(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response, Model model){
		paramBean.setUrl(getBasePath(request) + "admin/admin/list.shtml");
		int p = (Format.null2Zero(request.getParameter("p")) == 0) ? 1 : Format.null2Zero(request.getParameter("p"));
		paramBean.setPage(p);
		Pagination<Admin> pagination = adminService.getPagination(paramBean);
		request.setAttribute("pagination", pagination);
		return "admin/admin/list";
	}
	
	@RequestMapping(value = "/admin/add",method=RequestMethod.GET)
	public String adminAdd(HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("roles", adminService.getAll(Role.class));
		return "admin/admin/add";
	}
	
	@RequestMapping(value = { "/checkUsername" }, method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> checkUsername(HttpServletRequest request, HttpServletResponse response, Model model){
		Map<String, Object> data = new HashMap<String, Object>();
		String name = request.getParameter("name");
		String param = request.getParameter("param");
		if (StringUtils.isBlank(name) || StringUtils.isBlank(param) || !name.equals("username")) {
			data.put("status", "n");
			data.put("info", "参数错误");
			return data;
		}
		boolean isExists = adminService.usernameExists(param);
		if (isExists) {
			data.put("status", "n");
			data.put("info", "用户名已存在");
			return data;
		} else {
			data.put("status", "y");
			data.put("info", "通过验证");
			return data;
		}
	}
	
	@RequestMapping(value = "/admin/save", method=RequestMethod.POST)
	public String adminSave(Admin admin, HttpServletRequest request, HttpServletResponse response, Model model){
		admin.setPassword(Md5Util.encrypt(admin.getPassword()));
		admin.setIsEnabled((admin.getIsEnabled() != null && admin.getIsEnabled()) ? true : false);
		admin.setIsLocked(false);
		admin.setLoginFailureCount(0);
		Set<Role> rSet = new HashSet<Role>();
		String[] roleIds = request.getParameterValues("roleIds");
		if (roleIds != null && roleIds.length > 0) {
			for (String roleId : roleIds) {
				Role role = adminService.getById(Role.class, Long.valueOf(roleId));
				if (role == null) {
					continue;
				}
				rSet.add(role);
			}
		}
		admin.setRoles(rSet);
		adminService.save(admin);
		return "redirect:/admin/admin/list.shtml";
	}
	
	@RequestMapping(value = "/admin/edit", method=RequestMethod.GET)
	public String adminEdit(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("admin", adminService.getById(Admin.class, id));
		request.setAttribute("roles", adminService.getAll(Role.class));
		return "admin/admin/edit";
	}
	
	@RequestMapping(value = "/admin/update", method=RequestMethod.POST)
	public String adminUpdate(Admin admin, HttpServletRequest request, HttpServletResponse response, Model model){
		Admin pAdmin = adminService.getById(Admin.class, admin.getId());
		pAdmin.setEmail(admin.getEmail());
		pAdmin.setMobile(admin.getMobile());
		pAdmin.setIsEnabled((admin.getIsEnabled() != null && admin.getIsEnabled()) ? true : false);
		pAdmin.setRoles(null);
		Set<Role> rSet = new HashSet<Role>();
		String[] roleIds = request.getParameterValues("roleIds");
		if (roleIds != null && roleIds.length > 0) {
			for (String roleId : roleIds) {
				Role role = adminService.getById(Role.class, Long.valueOf(roleId));
				if (role == null) {
					continue;
				}
				rSet.add(role);
			}
		}
		pAdmin.setRoles(rSet);
		pAdmin.setDepartment(admin.getDepartment());
		pAdmin.setName(admin.getName());
		adminService.update(pAdmin);
		return "redirect:/admin/admin/list.shtml";
	}
	
	@RequestMapping(value = "/admin/view", method=RequestMethod.GET)
	public String adminView(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("admin", adminService.getById(Admin.class, id));
		request.setAttribute("roles", adminService.getAll(Role.class));
		return "admin/admin/view";
	}
	
	@RequestMapping(value = "/admin/editpassword", method=RequestMethod.GET)
	public String adminEditpassword(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("admin", adminService.getById(Admin.class, id));
		return "admin/admin/editpassword";
	}
	
	@RequestMapping(value = "/admin/updatepassword", method=RequestMethod.POST)
	public String adminUpdatepassword(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		String pPassword = request.getParameter("pPassword");
		String nPassword = request.getParameter("nPassword");
		String cfnPassword = request.getParameter("cfnPassword");
		if (StringUtils.isEmpty(pPassword) || StringUtils.isEmpty(nPassword) || StringUtils.isEmpty(cfnPassword)) {
			return ERROR_VIEW;
		}
		if (!cfnPassword.equals(nPassword)) {
			return ERROR_VIEW;
		}
		Admin pAdmin = adminService.getById(Admin.class, id);
		if (!Md5Util.encrypt(pPassword).equals(pAdmin.getPassword())) {
			return ERROR_VIEW;
		}
		pAdmin.setPassword(Md5Util.encrypt(nPassword));
		adminService.update(pAdmin);
		return "redirect:/admin/admin/list.shtml";
	}
	
	@RequestMapping(value = "/role/list", method=RequestMethod.GET)
	public String roleList(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response, Model model){
		paramBean.setUrl(getBasePath(request) + "admin/role/list.shtml");
		int p = (Format.null2Zero(request.getParameter("p")) == 0) ? 1 : Format.null2Zero(request.getParameter("p"));
		paramBean.setPage(p);
		Pagination<Role> pagination = adminService.getRolePage(paramBean);
		request.setAttribute("pagination", pagination);
		return "admin/role/list";
	}
	
	@RequestMapping(value = "/role/add", method=RequestMethod.GET)
	public String roleAdd(HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("permissions", adminService.get(Permission.class, null, "order by orders asc"));
		return "admin/role/add";
	}
	
	@RequestMapping(value = "/role/save", method=RequestMethod.POST)
	public String roleSave(Role role, HttpServletRequest request, HttpServletResponse response, Model model){
		role.setIsSystem((role.getIsSystem() != null && role.getIsSystem()) ? true : false);
		Set<Permission> pSet = new HashSet<Permission>();
		String[] permissionIds = request.getParameterValues("permissionIds");
		if (permissionIds != null && permissionIds.length > 0) {
			for (String permissionId : permissionIds) {
				Permission permission = adminService.getById(Permission.class, Long.valueOf(permissionId));
				if (permission == null) {
					continue;
				}
				pSet.add(permission);
			}
		}
		role.setPermissions(pSet);
		adminService.save(role);
		return "redirect:/admin/role/list.shtml";
	}
	
	@RequestMapping(value = "/role/edit", method=RequestMethod.GET)
	public String roleEdit(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("role", adminService.getById(Role.class, id));
		request.setAttribute("permissions", adminService.get(Permission.class, null, "order by orders asc"));
		return "admin/role/edit";
	}
	
	@RequestMapping(value = "/role/update", method=RequestMethod.POST)
	public String roleUpdate(Role role, HttpServletRequest request, HttpServletResponse response, Model model){
		Role pRole = adminService.getById(Role.class, role.getId());
		pRole.setName(role.getName());
		pRole.setDescription(role.getDescription());
		pRole.setIsSystem((role.getIsSystem() != null && role.getIsSystem()) ? true : false);
		pRole.setPermissions(null);
		Set<Permission> pSet = new HashSet<Permission>();
		String[] permissionIds = request.getParameterValues("permissionIds");
		if (permissionIds != null && permissionIds.length > 0) {
			for (String permissionId : permissionIds) {
				Permission permission = adminService.getById(Permission.class, Long.valueOf(permissionId));
				if (permission == null) {
					continue;
				}
				pSet.add(permission);
			}
		}
		pRole.setPermissions(pSet);
		adminService.update(pRole);
		return "redirect:/admin/role/list.shtml";
	}
	
	@RequestMapping(value = "/role/view", method=RequestMethod.GET)
	public String roleView(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("role", adminService.getById(Role.class, id));
		request.setAttribute("permissions", adminService.getAll(Permission.class));
		return "admin/role/view";
	}
	
	@RequestMapping(value = "/permission/list", method=RequestMethod.GET)
	public String permissionList(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response, Model model){
		paramBean.setUrl(getBasePath(request) + "admin/permission/list.shtml");
		int p = (Format.null2Zero(request.getParameter("p")) == 0) ? 1 : Format.null2Zero(request.getParameter("p"));
		paramBean.setPage(p);
		Pagination<Permission> pagination = adminService.getPermissionPage(paramBean);
		request.setAttribute("pagination", pagination);
		return "admin/permission/list";
	}
	
	@RequestMapping(value = "/permission/add", method=RequestMethod.GET)
	public String permissionAdd(HttpServletRequest request, HttpServletResponse response, Model model){
		return "admin/permission/add";
	}
	
	@RequestMapping(value = "/permission/save", method=RequestMethod.POST)
	public String permissionSave(Permission permission, HttpServletRequest request, HttpServletResponse response, Model model){
		adminService.save(permission);
		return "redirect:/admin/permission/list.shtml";
	}
	
	@RequestMapping(value = "/permission/edit", method=RequestMethod.GET)
	public String permissionEdit(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("permission", adminService.getById(Permission.class, id));
		return "admin/permission/edit";
	}
	
	@RequestMapping(value = "/permission/update", method=RequestMethod.POST)
	public String permissionUpdate(Permission permission, HttpServletRequest request, HttpServletResponse response, Model model){
		Permission pPermission = adminService.getById(Permission.class, permission.getId());
		pPermission.setName(permission.getName());
		pPermission.setDescription(permission.getDescription());
		pPermission.setPermission(permission.getPermission());
		pPermission.setOrders(permission.getOrders());
		adminService.update(pPermission);
		return "redirect:/admin/permission/list.shtml";
	}
	
	@RequestMapping(value = "/permission/view", method=RequestMethod.GET)
	public String permissionView(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("permission", adminService.getById(Permission.class, id));
		return "admin/permission/view";
	}
}
